//
//  THAddAddressViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/9.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THAddAddressViewController.h"
#import "DXLAddressPickView.h"
#import "SMAddressChosedViewController.h"
@interface THAddAddressViewController ()
@property(nonatomic, strong) NSMutableArray<NSArray*>                     *dataSouce;/**<  */
@property(nonatomic, strong) STButton                     *chosedButton;/**<  */
@property(nonatomic, strong) NSArray                     *code_array;/**<  */
@end

@implementation THAddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑地址";
    [self config_dataSouce];
    [self stoneobs_ui_configSubView];
    [self stoneobs_fun_st_setRightItemWithTitle:@"保存" titleColor:STONEOBS_UI_FIRST_TEXT_COLOR];
    // Do any additional setup after loading the view.
}
#pragma mark --configSubView
- (void)config_dataSouce{
    self.dataSouce = NSMutableArray.new;
    NSString * area = [NSString stringWithFormat:@"%@%@%@",self.addressModel.p_name,self.addressModel.c_name,self.addressModel.d_name];
    if (!self.addressModel) {
        area = @"请选择地区";
    }else{
        self.code_array = @[self.addressModel.p_code,self.addressModel.c_code,self.addressModel.d_code];
        
    }
    ({
       NSArray * array = @[
           [[STTools_TableEasyModel alloc] initWithTextString:@"收货人" accessoryView:[self textFiledFromPlaceHolder:@"收货人"]],
           [[STTools_TableEasyModel alloc] initWithTextString:@"手机号" accessoryView:[self textFiledFromPlaceHolder:@"手机号"]],
           [[STTools_TableEasyModel alloc] initWithTextString:@"地区" detailString:area],
           [[STTools_TableEasyModel alloc] initWithTextString:@"详细地址" accessoryView:[self textFiledFromPlaceHolder:@"详细地址"]],

       ];
        [self.dataSouce addObject:array];
    });
    
    [self.tableView reloadData];
}
- (UITextField*)textFiledFromPlaceHolder:(NSString*)placeholder{
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH*0.6, 50)];
    textFiled.textAlignment = NSTextAlignmentRight;
    textFiled.placeholder = placeholder;
    textFiled.font = [UIFont systemFontOfSize:13];
    textFiled.textColor = WH_UICOLOR_FROM_RGBA(0x999999);
    if (self.addressModel) {
        if ([placeholder isEqual:@"收货人"]) {
            textFiled.text = self.addressModel.name;
        }
        if ([placeholder isEqual:@"手机号"]) {
            textFiled.text = self.addressModel.phone;
        }
        if ([placeholder isEqual:@"详细地址"]) {
            textFiled.text = self.addressModel.detail;
        }
    }
    return textFiled;
}
#pragma mark --configSubView
- (void)stoneobs_ui_configSubView{

    
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 100)];
    
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 50)
                                                              title:@"设为默认地址"
                                                         titleColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                          titleFont:15
                                                       cornerRadius:0
                                                    backgroundColor:UIColor.whiteColor
                                                    backgroundImage:nil
                                                              image:ST_IMAGE_NAMED(@"wgx")];
    [footer addSubview:stoneobs_ui_button];
    [stoneobs_ui_button setImage:ST_IMAGE_NAMED(@"勾选") forState:UIControlStateSelected];
    stoneobs_ui_button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    stoneobs_ui_button.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {
        sender.selected = !sender.selected;
    }];
    self.chosedButton = stoneobs_ui_button;
    stoneobs_ui_button.selected = self.addressModel.is_default;
    
    STButton * button = [[STButton alloc] initWithFrame:CGRectMake(20, 70, UISCREEN_WIDTH - 40, 44)
                                                  title:@"删除地址"
                                             titleColor:FlatRed
                                              titleFont:15
                                           cornerRadius:4
                                        backgroundColor:UIColor.whiteColor
                                        backgroundImage:nil
                                                  image:nil];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    button.centerX = self.tableView.width / 2;
    footer.height = button.bottom;
    [footer addSubview:button];
    [button setClicAction:^(UIButton *sender) {
        [weakSelf stoneobs_fun_st_showAlertTitle:@"确定要删除这个地址吗？" message:@"" leftTitle:@"取消" rightTitle:@"删除" block:^(NSString *name) {
            if ([name isEqualToString:@"删除"]) {
                [weakSelf stoneobs_fun_on_slected_delete];
            }
        }];
    }];
    button.hidden = YES;
    if (self.addressModel) {
        button.hidden = NO;
    }
    self.tableView.tableFooterView = footer;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    [cell setSt_tableEasyModel:model];
    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    if ([model.textString isEqualToString:@"地区"]) {
        SMAddressChosedViewController * vc = SMAddressChosedViewController.new;
        [vc setOnSlectedhandle:^(NSArray * _Nonnull codeArray, NSArray * _Nonnull placeArray) {
            model.detailString = [placeArray componentsJoinedByString:@""];
            self.code_array = codeArray;
            [self.tableView reloadData];
        }];
        [self presentViewController:vc animated:NO completion:nil];
    }

    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (STTools_TableEasyModel*)modelFormText:(NSString*)text{
    for (STTools_TableEasyModel * model in self.dataSouce.stoneobs_fun_dissolveArray) {
        if ([model.textString containsString:text]) {
            return model;
        }
    }
    return nil;
}
- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    for (STTools_TableEasyModel * model in self.dataSouce.stoneobs_fun_dissolveArray) {
        if (model.accessoryView) {
            UITextField * textFiled = (id)model.accessoryView;
            if (!textFiled.text.length) {
                [SVProgressHUD showErrorWithStatus:textFiled.placeholder];
                return;
            }
        }else{
            if (!model.detailString.length) {
                [SVProgressHUD showErrorWithStatus:@"请选择地区"];
                return;
            }
        }
    }
    
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (self.addressModel.a_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"收货人"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"name"];
    });
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"手机号"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"phone"];
    });
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"详细地址"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"detail"];
    });
    ({
        if (self.code_array.count > 0) {
            [stoneobs_net_param_dic setObject:self.code_array[0] forKey:@"p_code"];
        }
        if (self.code_array.count > 1) {
            [stoneobs_net_param_dic setObject:self.code_array[1] forKey:@"c_code"];
        }
        if (self.code_array.count > 2) {
            [stoneobs_net_param_dic setObject:self.code_array[2] forKey:@"d_code"];
        }
    });
    
    if (self.chosedButton.selected) {
       [stoneobs_net_param_dic setObject:@"1" forKey:@"is_default"];
    }
    if (self.addressModel.a_id.length) {
        [stoneobs_net_param_dic setObject:self.addressModel.a_id forKey:@"id"];
    }
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/user/addresses"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"操作成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
}
- (void)stoneobs_fun_on_slected_delete{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.addressModel.a_id.length) {
        [stoneobs_net_param_dic setObject:self.addressModel.a_id forKey:@"id"];
    }
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"/v1/user/addresses"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumDelete
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
